﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;

namespace RH
{
    public partial class wfPlanillaMnt : EditPage
    {
      
        public const int _GRDLIST_IDCONREMU = 3;
        public const int _GRDLIST_STINHABILITA = 6;
        public const int _GRDLIST_STANULADO = 7;
       
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                this.LoadInPostBack();
                return;
            }
            this.LoadData();
        }

        public override void LoadInPostBack()
        {
            this.RegisterGeneralScripts();
        }

        public override void LoadInitialSettings()
        {
           this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
           Label lbl = (Label)this.Master.FindControl("lblTitle");
           lbl.Text = "Planilla";
        }

        //public override void LoadListControls()
        //{
        //    EPlanillaDet objEDet = new EPlanillaDet();
        //    ETablaPEDet objEDetPE = new ETablaPEDet();
        //    ECCosto objECCosto = new ECCosto();
        //    EEmpEstable objEEmp = new EEmpEstable();
        //    EBanco objEBanco = new EBanco();

        //    IBOQuery objBOCCosto = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CCosto));
        //    IBOQuery objBOBanco = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.Banco));
        //    MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
        //    RHBOQry.ITablaPE objBOIPE = (RHBOQry.ITablaPE)WCFHelper.GetObject<RHBOQry.ITablaPE>(typeof(RHBOQry.TablaPE));
        //    SYBOQry.IEmpresa objBOEmp = (SYBOQry.IEmpresa)WCFHelper.GetObject<SYBOQry.IEmpresa>(typeof(SYBOQry.Empresa));

        //    objEDet.IdTabla = ConstMultitabla.TIPO_DOCUMENTO;
        //    DataTable dt = objBOI.GetDetailByList(objEDet);
        //    WebHelper.LoadListControl(ddlidConRemu, dt, "dsAbrev", "idCodigo", true, true);

        //    objEBanco.IdBanco = "";
        //    dt = objBOBanco.GetList(objEBanco);
        //    WebHelper.LoadListControl(ddlidBcoAbono, dt, "dsBanco", "idBanco", true, true);
        //    WebHelper.LoadListControl(ddlidBcoCts, dt, "dsBanco", "idBanco", true, true);
        //}

        public override void DataToControls()
        {
            EPlanilla objE = new EPlanilla();
            IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla));
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objE.IdPlanilla = Request.QueryString["idPlanilla"];
            objE = (EPlanilla)objBO.GetByKey(objE);


            if (objE != null)
            {

                WebHelper.EntityToControl(objE, "IdPlanilla", txtidPlanilla);
                WebHelper.EntityToControl(objE, "DsPlanilla", txtdsPlanilla);
                WebHelper.EntityToControl(objE, "NuProcAnual", txtnuProcAnual);

            }

                EPlanillaDet objEPlaDet = new EPlanillaDet();

                RHBOQry.Planilla objBOPerC = (RHBOQry.Planilla)WCFHelper.GetObject<RHBOQry.Planilla>(typeof(RHBOQry.Planilla));
                objEPlaDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                objEPlaDet.IdPlanilla = Request.QueryString["idPlanilla"];
                DataTable dt = objBOPerC.GetByParentKeyPlaniDet(objEPlaDet);
                  
                this.GridSetDataBinding(grdList, dt);
                this.GridSort(grdList, "nuSecuen", SortDirection.Ascending);

       }

        public override void RegisterGeneralScripts()
        {
            txtidPlanilla.Attributes.Add("readonly", "true");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validateEditForm(key){");
 
            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtdsPlanilla.ClientID + "','Ingrese Descripcion Planilla');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("var varRpta = isEmptyControl('" + this.txtnuProcAnual.ClientID + "','Ingrese Numero de Proceso Anual');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");

            sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
        }

        public void RegisterEditPopupScripts()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("var varRet = modalDialog('../RH/wfConcepRemu.aspx',725,400);");
            sb.AppendLine("if(varRet==null)");
            sb.AppendLine("return false;");
            sb.AppendLine("ctl = document.getElementById('" + this.hdnidConRemu.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[0];");
            sb.AppendLine("ctl = document.getElementById('" + this.txtidConRemu.ClientID + "');");
            sb.AppendLine("ctl.value = varRet[1];");
            sb.AppendLine("return false;");
            this.txtidConRemu.OnClientClick = sb.ToString();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "", sb.ToString(), true);
          
            StringBuilder sb2 = new StringBuilder();

            sb2.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
            //sb.AppendLine("debugger;");
            if (this.GridEditAction == GridEditAction.AddNew)
            {
               sb2.AppendLine("varRpta = gridFindCellValueInRow('" + grdList.ClientID + "',new Array('" + _GRDLIST_IDCONREMU + "'), new Array(document.getElementById('" + this.hdnidConRemu.ClientID + "').value),'Ya existe el concepto de Remuneracion');");
               sb2.AppendLine("if(varRpta==true)");
               sb2.AppendLine("return !varRpta;");
            }

            sb2.AppendLine("varRpta = isEmptyControl('" + this.txtnuSecuen.ClientID + "','Ingrese Numero de Secuencia.');");
            sb2.AppendLine("if(varRpta==true)");
            sb2.AppendLine("return !varRpta;");
            sb2.AppendLine("return true;}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb2.ToString(), true);

            this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
            this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";

        }
       
        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
           if (e.Item == null)
              return;

           switch (e.Item.Value)
           {
              case ConstMenuToolbarValue.BUTTON_SAVE:
              case ConstMenuToolbarValue.BUTTON_SAVENEW:
                 if (this.FormEditAction != FormEditAction.Delete)
                    this.SaveData(e.Item.Value);
                 else
                    this.DeleteData();
                 break;

              case ConstMenuToolbarValue.BUTTON_EXIT:
                 this.Response.Redirect("wfPlanillaBnd.aspx?Filter=1");
                 break;
           }

        }

        public override void SaveData(String key)
        {
            if (this.ValidateData() == false)
                return;

            IEntityBase objE = (IEntityBase)this.CreateEntitySet();

            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Planilla));

            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            {

                case FormEditAction.AddNew:
                case FormEditAction.Copy:
                    strMsg = "Se ha registrado la Planilla : " + strRet[0].ToString();
                    break;
                default:
                    strMsg = "Se ha modificado la Planilla : " + txtidPlanilla.Text + "  " + txtdsPlanilla.Text;
                    break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfPlanillaBnd.aspx?Filter=1");
         
        }
       
        protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

            switch (e.CommandName)
            {
                case ConstGridRowCommand.GRIDEDIT:
                    this.lblTitlePopup.Text = "Detalle Planilla (Editar)";
                    this.GridEditAction = GridEditAction.Edit;
                   this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;
                case ConstGridRowCommand.GRIDDELETE:
                    this.lblTitlePopup.Text = "Detalle Planilla (Dar de Baja)";
                    this.GridEditAction = GridEditAction.Delete;
                    this.mdlPopup.Show();
                    this.LoadDataEditPopup(grdList, this.EditRowIndex);
                    this.RegisterEditPopupScripts();
                    break;
            }
        }

        protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
                { e.Row.ForeColor = System.Drawing.Color.Red; }

                CheckBox chk = (CheckBox)e.Row.FindControl("chkstDesHabilita");
                if (e.Row.Cells[_GRDLIST_STINHABILITA].Text == ConstFlagEstado.ACTIVADO)
                {
                   chk.Checked = true;
                }

            }

        }
        
        protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_NEW:
                    this.GridEditAction = GridEditAction.AddNew;
                    this.lblTitlePopup.Text = "Planilla (Nuevo)";
                    this.mdlPopup.Show();
                    this.ClearEditPopup();
                    this.LoadDataEditPopup(grdList, -1);
                    this.RegisterEditPopupScripts();
                    break;
            }

        }

        protected void bttOkPopup_Click(object sender, EventArgs e)
        {

            DataTable dt = (DataTable)this.DataSource;
            DataRow dr = null;

            if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
            {
               
                dr = dt.NewRow();
            }
            else
            {
                dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
            }

            if (this.GridEditAction != GridEditAction.Delete)
            {
                dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
                dr["IdPlanilla"] = Request.QueryString["IdPlanilla"];
                dr["idConRemu"] = this.hdnidConRemu.Value.ToString();
                dr["dsConRemu"] = this.txtidConRemu.Text.ToString();
                dr["nuSecuen"] = this.txtnuSecuen.Text.ToString();

                if (chkstHabilitado.Checked)
                   dr["stInhabilita"] = ConstFlagEstado.ACTIVADO;
                else
                   dr["stInhabilita"] = ConstFlagEstado.DESACTIVADO;

                dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;

            }
            else
            {
                dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
            }

            if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
            {
                dt.Rows.Add(dr);
            }


            this.GridSetDataBinding(grdList, dt);
        }
       
        public override void LoadDataEditPopup(GridView grid, int rowIndex)
        {
            this.ClearEditPopup();
            this.LockControlsPopup();

            DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, rowIndex);

            if (dr == null)
                return;

            WebHelper.RowToControl(dr, "idConRemu", hdnidConRemu);
            WebHelper.RowToControl(dr, "dsConRemu", txtidConRemu);
            WebHelper.RowToControl(dr, "nuSecuen", txtnuSecuen);
            WebHelper.RowToControl(dr, "stInhabilita", chkstHabilitado);

        }

        public new void ClearEditPopup()
        {
           this.chkstHabilitado.Checked = false;
           this.txtnuSecuen.Text = "0";
           this.txtidConRemu.Text = "";
           this.hdnidConRemu.Value = "";

        }

        public void LockControlsPopup()
        {
            //switch (this.GridEditAction)
            //{
            //    case GridEditAction.AddNew:
            //    case GridEditAction.Edit:
            //        this.txtfeBajaDH.Enabled = false;
            //        this.ddlidMotivoBajaDH.Enabled = false;
            //        break;
            //    case GridEditAction.Delete:
            //        this.txtfeBajaDH.Enabled = true;
            //        this.ddlidMotivoBajaDH.Enabled = true;
            //        this.txtdsApePaternoDH.Enabled = false;
            //        this.txtdsApeMaternoDH.Enabled = false;
            //        this.txtdsNombresDH.Enabled = false;
            //        this.ddlidTipoDocDH.Enabled = false;
            //        this.txtnuDocDH.Enabled = false;
            //        this.txtfeNacimientoDH.Enabled = false;
            //        this.ddlidGeneroDH.Enabled = false;
            //        this.ddlidVincFamDH.Enabled = false;
            //        this.ddlidVincFamDH.Enabled = false;
            //        this.ddlidTipoDocVincFamDH.Enabled = false;
            //        this.txtnuDocVincFamDH.Enabled = false;
            //        this.txtfeConcepDH.Enabled = false;
            //        this.txtnuCodLDN.Enabled = false;
            //        this.txtnuTelefonoDH.Enabled = false;
            //        this.txtdsEmailDH.Enabled = false;
            //        this.txtdsUbigeo.Enabled = false;
            //        this.ddlidTipoVia.Enabled = false;
            //        this.txtdsNombreVia.Enabled = false;
            //        this.txtnuVia.Enabled = false;
            //        this.txtnuDpto.Enabled = false;
            //        this.txtnuInterior.Enabled = false;
            //        this.txtdsManzana.Enabled = false;
            //        this.txtdsLote.Enabled = false;
            //        this.txtdsKilometro.Enabled = false;
            //        this.txtdsBlock.Enabled = false;
            //        this.txtdsEtapa.Enabled = false;
            //        this.ddlidTipoZona.Enabled = false;
            //        this.txtdsNombZona.Enabled = false;
            //        this.txtdsReferen.Enabled = false;
            //        this.txtdsUbigeo2.Enabled = false;
            //        this.ddlidTipoVia2.Enabled = false;
            //        this.txtdsNombreVia2.Enabled = false;
            //        this.txtnuVia2.Enabled = false;
            //        this.txtnuDpto2.Enabled = false;
            //        this.txtnuInterior2.Enabled = false;
            //        this.txtdsManzana2.Enabled = false;
            //        this.txtdsLote2.Enabled = false;
            //        this.txtdsKilometro2.Enabled = false;
            //        this.txtdsBlock2.Enabled = false;
            //        this.txtdsEtapa2.Enabled = false;
            //        this.ddlidTipoZona2.Enabled = false;
            //        this.txtdsNombZona2.Enabled = false;
            //        this.txtdsReferen2.Enabled = false;
            //        break;
            //}
        }

        //public override void DeleteData()
        //{
        //    IEntityBase objE = (IEntityBase)this.CreateEntitySet();
        //    IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.Personal));
        //    objPro.DeleteData(objE);

        //    this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Se anulo el Personal  : " + txtidPersonal.Text, "wfPersonalBnd.aspx?Filter=1");

        //}

        public override Object CreateEntitySet()
        {

           foreach (GridViewRow grdRow in grdList.Rows)
           {
              CheckBox ctlChk = (CheckBox)grdRow.FindControl("chkstDesHabilita");
              DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, Convert.ToInt32(grdRow.RowIndex));
              if (ctlChk.Checked)
              {
                
                 dr["stInhabilita"] = ConstFlagEstado.ACTIVADO;

              }
              else {
                 dr["stInhabilita"] = ConstFlagEstado.DESACTIVADO;
              }


           }
            EPlanilla objE = new EPlanilla();

            if (this.FormEditAction == FormEditAction.AddNew || this.FormEditAction == FormEditAction.Copy)
                objE.EntityState = EntityState.Added;
            else
            {
                IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla)); 
                objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                objE.IdPlanilla = txtidPlanilla.Text;
                objE = (EPlanilla)objBO.GetByKey(objE);

                if (this.FormEditAction == FormEditAction.Edit)
                    objE.EntityState = EntityState.Modified;
                if (this.FormEditAction == FormEditAction.Delete)
                    objE.EntityState = EntityState.Deleted;

            }

            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();

            WebHelper.ControlToEntity(txtidPlanilla, objE, "IdPlanilla");
            WebHelper.ControlToEntity(txtdsPlanilla, objE, "DsPlanilla");
            WebHelper.ControlToEntity(txtnuProcAnual, objE, "NuProcAnual");

            if (this.FormEditAction == FormEditAction.Delete)
            {
                objE.StAnulado = ConstFlagEstado.ACTIVADO;
            }
            else
            {
                objE.StAnulado = ConstFlagEstado.DESACTIVADO;
            }

            DataTable dt = (DataTable)this.DataSource;
           
            //this.ClearDeletedRow(this.DataSource, "stAnulado");

            IList<EPlanillaDet> colE = new List<EPlanillaDet>();

            for (int intTypeUpd = 0; intTypeUpd <= 1; intTypeUpd++)
            {
                DataTable dtChange = null;
                if (intTypeUpd == 0)
                    dtChange = dt.GetChanges(DataRowState.Added);
                else
                    dtChange = dt.GetChanges(DataRowState.Modified);


                if (dtChange != null)
                {
                    foreach (DataRow drDet in dtChange.Rows)
                    {
                        EPlanillaDet objEDet = DataHelper.CopyDataRowToEntity<EPlanillaDet>(drDet, typeof(EPlanillaDet));

                        if (drDet.RowState == DataRowState.Added)
                            objEDet.EntityState = EntityState.Added;

                        if (drDet.RowState == DataRowState.Modified)
                        {
                            if (objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                                objEDet.EntityState = EntityState.Modified;
                            else
                                objEDet.EntityState = EntityState.Deleted;
                        }

                        colE.Add(objEDet);
                    }
                }
            }

            EPlanillaSet objESet = new EPlanillaSet();

            objESet.Planilla = objE;
            objESet.ColPlanilla = colE; 

            return objESet;
        }

    }
}